<template>
  <div class="wrap">
    <div class="warp_auto">
      <div class="warp_top">
        <div class="jiansuo-box">
          <span class="label">时间模式：</span>
          <el-select v-model="form.region" class="input" clearable>
            <el-option
              v-for="item in options"
              :key="item.id"
              :value="item.label"
            />
          </el-select>
        </div>
        <div class="jiansuo-box">
          <span class="label">日期：</span>
          <el-date-picker
            v-model="form.value2"
            type="daterange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </div>
        <div class="jiansuo-box">
          <el-button type="primary" @click="onSubmit" class="btn">检索</el-button>
        </div>
      </div>
      <el-card class="echars_four">
        <div class="echars_three">
          <div slot="header">
            <div style="text-align: center;height: 100px;margin-top: 5px;">总入量：{{
                this.in === "" ? "0.00" : this.in
              }}
            </div>
          </div>
          <div slot="header">
            <div style="text-align: center;height: 100px;">总出量：{{ this.out === "" ? "0.00" : this.out }}</div>
          </div>
          <div slot="header">
            <div style="text-align: center;height: 100px;">总平衡量：{{ this.balance === "" ? "0.00" : this.balance }}</div>
          </div>
        </div>
        <div class="echars_three" style="margin-left: 5px;">
          <div v-if="ehartShow1">
            <img src="../../icons/img/none.png" class="img" alt>
            <span class="fon">暂无数据</span>
          </div>
          <div id="main1" style="float: left; width: 100%; height: 300px"/>
        </div>
      </el-card>

      <el-card class="echars_four">
        <div v-if="ehartShow4">
          <img src="../../icons/img/none.png" class="img4" alt>
          <span class="fon">暂无数据</span>
        </div>
        <div id="main4" style="float: left; width: 100%; height: 300px"/>
      </el-card>
      <el-card>
        <el-popover
          placement="top-start"
          width="60"
          trigger="hover"
          content="导出到Excel表"
        >
          <el-button
            slot="reference"
            type="primary"
            style="float:right; margin-bottom: 10px"
            @click="Excel"
          >导出
            <i class="el-icon-question"/>
          </el-button>
        </el-popover>
        <el-table
          height="250px"
          stripe
          :header-cell-style="{ background: '#d2e0f9', color: '#606266' }"
          :data="dataList"
          style="width: 100%"
        >
          <el-table-column label="日期" width="180">
            <template slot-scope="scope">
            <span>{{
                scope.row.dataTime == null
                  ? scope.row.describe
                  : scope.row.dataTime
              }}</span>

            </template>
          </el-table-column>
          <el-table-column prop="dosageSum" label="入量"/>
          <el-table-column prop="outSum" label="出量"/>
          <el-table-column prop="balanceSum" label="平衡量"/>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  inputAndOutputAmountGetDateAnalyze,
  inputAndOutputAmountGetDateTotal
} from '@/api/table'
import echarts from 'echarts'
import axios from 'axios'
import {getTenantId} from "@/utils/auth";

export default {
  data() {
    return {
      ehartShow1: true,
      ehartShow3: true,
      ehartShow4: true,
      form: {
        region: '',
        types: 'day',
        statisticTimeType: '',
        endTime: '',
        startTime: '',
        value2: ['', ''],
      },
      balance: '',
      in: '',
      out: '',
      dataList: [],
      patientId: "",
      options: [
        {
          id: '0',
          value: '0',
          label: '按护理单天'
        },
        {
          id: '1',
          value: '1',
          label: '按自然天'
        }
      ],
      types: [
        {
          id: '0',
          value: 'day',
          label: '按天'
        },
        {
          id: '1',
          value: 'hour',
          label: '按小时'
        }
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  mounted() {
    this.data = this.$store.state.user.severFall;
    this.ehartShow1 = true;
    this.ehartShow3 = true;
    this.ehartShow4 = true;

    if (typeof this.data.patient_id == "string" && this.data.patient_id.length > 0) {
      this.patientId = this.data.patient_id;
    } else {
      this.$message({message: "请先选择病人", type: "warning"});
    }
  },
  methods: {
    onSubmit() {
      if (this.form.region == "") {
        this.$message({
          message: "请选择时间模式",
          type: "warning"
        });
        return;
      }
      if (this.form.types == "") {
        this.$message({
          message: "请选择统计方式",
          type: "warning"
        });
        return;
      }
      if (this.form.value2[0] == "" || this.form.value2[1] == "") {
        this.$message({
          message: "请选择日期",
          type: "warning"
        });
        return;
      }
      if (this.form.types == 0) {
        this.form.statisticTimeType = "day";
      } else {
        this.form.statisticTimeType = "hour";
      }
      this.patientId = this.data.patient_id;
      if (this.form.region == '按护理单天') {
        this.form.startTime = this.form.value2[0] + ' 07:00:00';
        this.form.endTime = this.form.value2[1] + ' 07:00:00';
      } else if (this.form.region == '按自然天') {
        this.form.startTime = this.form.value2[0];
        this.form.endTime = this.form.value2[1];
      }
      //清空图表
      var myChart1 = echarts.init(document.getElementById('main1'));
      // var myChart2 = echarts.init(document.getElementById('main3'));
      var myChart4 = echarts.init(document.getElementById('main4'));
      myChart1.clear();
      // myChart2.clear();
      myChart4.clear();
      this.dataList = [];
      // 出入量占比总数和饼图
      inputAndOutputAmountGetDateTotal({
        statisticTimeType: this.form.statisticTimeType,
        patientId: this.patientId,
        startTime: this.form.startTime,
        endTime: this.form.endTime,
        newOrOld: "new",
      }).then((res) => {
        if (res.code == 200) {
          //统计出入量
          this.balance = res.data.balanceTotalSum;
          this.in = res.data.dosageTotalSum;
          this.out = res.data.outTotalSum;
          //出入量饼图

          var arr = [
            {value: res.data.dosageTotalSum, name: '入量'},
            {value: res.data.outTotalSum, name: '出量'}
          ];
          myChart1.setOption({
            title: {
              text: '出入量占比', // 主标题
              x: 'center' // x轴方向对齐方式
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}  {c} ({d}%)'
            },
            legend: {
              type: 'scroll',
              orient: 'vertical',
              left: 'left',
              top: 20,
              bottom: 20,
              data: ['出量', '入量']
            },
            series: [
              {
                name: '',
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: arr,
                label: {
                  normal: {
                    formatter: ' {b}',
                    borderWidth: 20,
                    borderRadius: 4,
                  }
                }
              }
            ]
          })
          this.ehartShow1 = false;
          /**
           //出量分析
           var arrOut = [
           {value:res.data.pissTotalSum, name:'尿量'},
           {value:res.data.drainageTotalSum, name:'引流量'}
           ];
           myChart2.setOption({
              title: {
                text: '出量分析',
                x: 'center'
              },
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {c} ({d}%)'
              },
              legend: {
                type: 'scroll',
                orient: 'vertical',
                left: 'left',
                top: 20,
                bottom: 20,
                data: ['尿量','引流量']
              },
              series: [
                {
                  name: '',
                  type: 'pie',
                  radius: '55%',
                  center: ['50%', '50%'],
                  data: arrOut,
                  label: {
                    normal: {
                      formatter: ' {b}',
                      borderWidth: 20,
                      borderRadius: 4,
                    }
                  }
                }
              ]
            })
           this.ehartShow3 = false
           **/
        } else {
          this.ehartShow1 = true;
          this.ehartShow3 = true;
        }
        // 统计分析--出入量--日期分析
        inputAndOutputAmountGetDateAnalyze({
          statisticTimeType: this.form.statisticTimeType,
          patientId: this.patientId,
          startTime: this.form.startTime,
          endTime: this.form.endTime,
          newOrOld: "new",
        }).then((res) => {
          if (res.code == 200) {
            var balanceArr = [];
            var dataTimeArr = [];
            var dosageSumArr = [];
            var outSumArr = [];
            var myChart4 = echarts.init(document.getElementById('main4'));
            console.log(res.data);
            if (res.data.length > 0) {
              this.ehartShow4 = false;
              for (var da of res.data) {
                if (da.dataTime != null) {
                  balanceArr.push(da.balanceSum);
                  if (this.form.statisticTimeType == "hour") {
                    dataTimeArr.push(da.dataTime + ":00");
                  } else {
                    dataTimeArr.push(da.dataTime);
                  }
                  dosageSumArr.push(da.dosageSum);
                  outSumArr.push(da.outSum);
                }
              }
              myChart4.setOption({
                title: {
                  text: '日期分析',
                  x: 'center'
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b} - {c}'
                },
                legend: {
                  left: 'center',
                  top: 'bottom',
                  data: ['入量', '出量', '平衡量']
                },
                xAxis: [
                  {
                    type: 'category',
                    data: dataTimeArr,
                    axisPointer: {
                      type: 'shadow'
                    }
                  }
                ],
                yAxis: [{}, {}],
                series: [
                  {
                    name: '入量',
                    type: 'line',
                    data: dosageSumArr
                  },
                  {
                    name: '出量',
                    type: 'line',
                    data: outSumArr
                  },
                  {
                    name: '平衡量',
                    type: 'line',
                    data: balanceArr
                  }
                ]
              });
              var listData = [];
              if (res.data.length > 0) {
                this.ehartShow4 = false;
                for (var da of res.data) {
                  if (da.dataTime != null) {
                    if (this.form.statisticTimeType == "hour") {
                      da.dataTime += ":00";
                    }
                  }
                  listData.push(da);
                }
                this.dataList = listData;
              }

            } else {
              this.ehartShow4 = true;
            }
          } else {
            this.ehartShow4 = true;
          }
        });
      });

    },
    // 导出
    Excel() {
      if (this.form.types == 0) {
        this.form.statisticTimeType = "day";
      } else {
        this.form.statisticTimeType = "hour";
      }
      this.data = this.$store.state.user.severFall;
      this.patientId = this.data.patient_id;
      if (this.form.region === '按护理单天') {
        this.form.startTime = this.form.value2[0] + ' 07:00:00';
        this.form.endTime = this.form.value2[1] + ' 07:00:00';
      } else if (this.form.region === '按自然天') {
        this.form.startTime = this.form.value2[0];
        this.form.endTime = this.form.value2[1];
      }
      axios({
        url: "/api/inOutAmount/downloadInOutTotal", //打包
        method: 'post',
        responseType: 'blob', // 也可以使用blob
        headers:{
          'tenantId' : getTenantId()
        },
        data: {
          statisticTimeType: this.form.statisticTimeType,
          patientId: this.patientId,
          startTime: this.form.startTime,
          endTime: this.form.endTime,
          newOrOld: "new",
        }
      })
        .then((res) => {
          console.log(res)
          if (res) {
            const blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel;charset=utf-8'
            }) // res就是接口返回的文件流了
            const objectUrl = URL.createObjectURL(blob)
            const elink = document.createElement('a')
            elink.download = '出入量统计信息.xls' // 下载文件名称,
            elink.style.display = 'none'
            elink.href = objectUrl
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          }
        })
        .catch(function (error) {
          this.$message({
            message: "导出错误",
            type: "warning"
          });
          console.log(error)
        })
    }
  }
}
</script>

<style scoped>
.total ul li {
  list-style-type: none;
  float: left;
  margin: 0 23% 0 -33px;
  line-height: 1px;
  font-size: 16px;
  font-weight: bold;
}

.total ul li span {
  font-size: 16px;
  font-weight: 700;
  color: #f90;
}

.echars_three {
  width: 48%;
  height: 300px;
  border-radius: 4px;
  border: 1px solid #dcdee2;
  float: left;
}

.echars_four {
  width: 100%;
  height: 330px;
  margin: 15px 0 15px 0;
  border-radius: 4px;
  border: 1px solid #dcdee2;
  float: left;
}

.img {
  width: 72% !important;
  height: auto !important;
  float: left;
  margin-left: 68px !important;
  margin-top: 35px !important;
}

.img4 {
  width: 29%;
  height: auto;
  margin: 0 571px;
}

.fon {
  font-weight: bold;
  font-size: 16px;
  color: rgb(102, 102, 102);
  float: left;
  width: 100%;
  text-align: center;
}
</style>

